import { store } from "@/store";
import { defineStore } from "pinia";
import RechargeApi, {
  type RechargeListQuery,
  type RechargeItemType,
  type RechargeForm,
} from "@/api/user/recharge";

export const useRechargeStore = defineStore("user-recharge", () => {
  const list = ref<RechargeItemType[]>([]);

  const totalCount = ref(0);

  const totalPage = ref(0);

  const loading = reactive({
    list: false,
    create: false,
    update: false,
    delete: false,
  });

  async function fetchRechargeList(params: RechargeListQuery) {
    loading.list = true;
    const response = await RechargeApi.getRechargeList(params);
    loading.list = false;
    if (response) {
      list.value = response.records;
      totalCount.value = response.total_count;
      totalPage.value = response.total_page;
    }
  }

  async function fetchCreateRecharge(data: Partial<RechargeForm>) {
    loading.create = true;
    await RechargeApi.createRecharge(data);
    loading.create = false;
  }

  async function fetchUpdateRecharge(data: Partial<RechargeForm>) {
    loading.update = true;
    await RechargeApi.updateRecharge(data);
    loading.update = false;
  }

  async function fetchDeleteRecharge(id: number) {
    loading.delete = true;
    await RechargeApi.deleteRecharge(id);
    loading.delete = false;
  }

  return {
    list,
    totalCount,
    totalPage,
    loading,
    fetchRechargeList,
    fetchCreateRecharge,
    fetchUpdateRecharge,
    fetchDeleteRecharge,
  };
});

export const useRechargeStoreHook = () => {
  return useRechargeStore(store);
};
